// pages/cart/index.js
import {getSetting,chooseAddress,openSetting,showModal} from '../../utils/asyncWx.js'
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
  data:{
    address: {},
    cart:[],
    allchecked:false,
    totalPrice:0,
    totaNum:0
  },
  onShow(){
    const address=wx.getStorageSync("address");
    const cart=wx.getStorageSync("cart") ||[];
    this.setData({address});
    this.setCart(cart);
  },
  async handleChooseAddress(e) {
    console.log("获取地址");
    try {
      //获取授权状态
      const res1 = await getSetting();
      const scopeAddress = res1.authSetting["scope.address"];
      //判断授权状态
      if (scopeAddress === false) {
        await openSetting();
      }
      //调用api
      const address = await chooseAddress();
      //把值设置到缓存当中。
      wx.setStorageSync("address", address);
    } catch (error) {
      console.log(error);
    }
  },
  handItemchange(e){
    const goods_id=e.currentTarget.dataset.id;
    let {cart}=this.data;
    let index=cart.findIndex(v=>v.goods_id===goods_id);
    cart[index].checked=!cart[index].checked;
    this.setCart(cart);
  },
  //封装
  setCart(cart){
    let allchecked=true
    let totalPrice=0;
    let totaNum=0;
    cart.forEach(v => {
      if(v.checked){
        totalPrice+=v.num*v.goods_price;
        totaNum+=v.num;
      }else{
        allchecked=false
      }
    });
    allchecked=cart.length!=0?allchecked:false;
    this.setData({
      cart,
      allchecked,
      totalPrice,
      totaNum
    });
    wx.setStorageSync('cart', cart);
  },
  //全选
  handleItemAllchange(){
    let {cart,allchecked}=this.data;
    allchecked=!allchecked;
    cart.forEach(v=>v.checked=allchecked);
    this.setCart(cart);
  },
  //商品数量加减
 async handleItemNumEdit(e){
    const {operation,id}=e.currentTarget.dataset;
    let {cart}=this.data;
    const index=cart.findIndex(v=>v.goods_id===id);
    if(cart[index].num===1&&operation===-1){
      const res=await showModal({content:"您是否要删除？"});
      if(res.confirm){
        cart.splice(index,1)
        this.setCart(cart);
      }
    }else{
      cart[index].num+=operation;
      this.setCart(cart);
    }  
  }
})